package com.spice.im.group;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.beem.push.utils.AsyncTask;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.speed.im.login.EncryptionUtil;
import com.spice.im.ContactFrameActivity;
import com.spice.im.FlippingLoadingDialog;
import com.spice.im.R;
import com.stb.core.chat.ContactGroup;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.service.aidl.IRoster;
import com.stb.isharemessage.service.aidl.IXmppFacade;
import com.stb.isharemessage.utils.BeemConnectivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import com.spice.im.group.SortAdapter2.CheckBoxAndLinearListener;
import com.spice.im.ui.HandyTextView;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onMiddleImageButtonClickListener;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;

/**
 *
 * @author buptzhaofang@163.com Dec 5, 2015 10:54:23 PM
 *
 */
public class GroupPickContactsActivity extends Activity implements
		OnClickListener {
	private Context mContext;
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
      LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
	private static final Intent SERVICE_INTENT = new Intent();
	static {
		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));
	}
	private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
    protected FlippingLoadingDialog mLoadingDialog;
    private HeaderLayout mHeaderLayout;
	
    private static final String TAG = "GroupDetailsActivity";
    private final ServiceConnection mServConn = new BeemServiceConnection();
    
    protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}		    
	protected void showLoadingDialog(String text) {
		if (text != null) {
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}
//	private boolean isWork = false;
//	private String CurrentUid = "";
//	private String CurrentUsername = "";
	private String CurrentUserAvatorPath = "";
    private String groupId;
    private String groupName;
    
	private static final int MESSAGE_UPDATE_SEND_BTN = 0x00020001;
	private static final int MESSAGE_BIND_FRIEND_LIST = 0x00020002;

	private ImageView avatar;
	private ListView batchFriendList;

//	private Button sureBtn;

	private ImageLoader mLoader;
	private TextView batchTransferTitle;

	private List<ContactGroup> friends_cGroup;//ContactFrameActivity.java 中传递过来
	private ContactGroup cGroup;
	int cgrouptype = 0;
	private List<SortModel2> friends;
	//ContactFrameActivity.java页面中
	//intent.putExtra("friends", (Serializable)cGroups);  
	private SortAdapter2 adapter;
	private CharacterParser characterParser;
	private PinyinComparator pinyinComparator;

	/** 是否为一个新建的群组 */
	protected boolean isCreatingNewGroup;
	/** 是否为单选 */
	private boolean isSignleChecked;
	/** group中一开始就有的成员 */
	private List<String> exitingMembers = new ArrayList<String>();;
	private EditText query;
	private ImageButton clearSearch;
	List<String> member;
	int type;
	String id, txt, link_share;

//	LoadingFragment dialog;
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case MESSAGE_UPDATE_SEND_BTN:
//					int count = (int) msg.obj;
					String count = (String) msg.obj;
		//			sureBtn.setText("确定(" + count + ")");
					break;
				case MESSAGE_BIND_FRIEND_LIST:
					bindAdapter();
					break;
			}
		}
	};

	private CheckBoxAndLinearListener listener = new CheckBoxAndLinearListener() {

		@Override
		public void onChecked(int count) {
			// TODO Auto-generated method stub
			mHandler.obtainMessage(MESSAGE_UPDATE_SEND_BTN, count+"")
					.sendToTarget();
		}

		@Override
		public void onLinearClicked(int position) {

		}
	};

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		
		member = (List<String>) getIntent().getStringArrayListExtra("member");
		type = getIntent().getIntExtra("type", 0);
		id = getIntent().getStringExtra("id");
		link_share = getIntent().getStringExtra("link_share");
		txt = getIntent().getStringExtra("txt");
		setTitle("选择好友");
//		sureBtn = (Button) actionBarView.findViewById(R.id.sendBtn);
//		sureBtn.setText("确定");
//		sureBtn.setOnClickListener(this);
//		sureBtn.setVisibility(View.VISIBLE);
		setContentView(R.layout.activity_batch_transfer);
		mContext = this;
		mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
		mHeaderLayout = (HeaderLayout) findViewById(R.id.login_header);
//		mHeaderLayout.init(HeaderStyle.DEFAULT_TITLE);
		mHeaderLayout.init(HeaderStyle.TITLE_CHAT);
		mHeaderLayout.setTitleChat(R.drawable.ic_chat_dis_1,
				R.drawable.bg_chat_dis_active, "发起群聊",
				"",
				R.drawable.ic_menu_invite,//ic_menu_invite  ic_topbar_profile
				new OnMiddleImageButtonClickListener(),
				R.drawable.return2,
				new OnRightImageButtonClickListener());
		
        // 获取传过来的groupid
        groupId = getIntent().getStringExtra("groupId");
        groupName = getIntent().getStringExtra("groupName");
        
//        friends_cGroup =  (List<ContactGroup>)getIntent().getSerializableExtra("friends");
//        Log.e("================GroupPickContactsActivity.java ================", "++++++++++++++friends_cGroup1111++++++++++++++"+friends_cGroup);
//        if(friends_cGroup!=null
//        		&& friends_cGroup.size()!=0){
//        	
//        	for(int i=0;i<friends_cGroup.size();i++){
//        		cGroup = (ContactGroup)friends_cGroup.get(i);
//        		Log.e("================GroupPickContactsActivity.java ================", "++++++++++++++friends_cGroup2222++++++++++++++"+cGroup.toXML());
//        		cgrouptype = cGroup.getType();////0 contact,1 group
//        		if(cgrouptype == 1)
//        			friends_cGroup.remove(i);
//        	}
//        	friends = filterExistGroupMember(bindFriendListToSortModel2(friends_cGroup));
//        }
        
		mLoader = ImageLoader.getInstance();
		avatar = (ImageView) findViewById(R.id.batch_avatar);
		batchFriendList = (ListView) findViewById(R.id.batch_friend_list);
		batchTransferTitle = (TextView) findViewById(R.id.batch_transfer_title);
		batchTransferTitle.setText("选择好友");
		if (type == 1) {
			batchTransferTitle.setText("选择群");
			batchTransferTitle.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
//					Intent intent = new Intent(GroupPickContactsActivity.this, GroupsActivity.class);
//					intent.putExtra("id", id);
//					intent.putExtra("link_share", link_share);
//					intent.putExtra("txt", txt);
//					startActivity(intent);
				}
			});
		}
		
		mLoader.displayImage(//UserManager.getInstance().getUser().getAvatarUrl()
				CurrentUserAvatorPath, avatar,
				Options.getOptions(UIUtils.dip2px(this, ConstantConfig.AVATAR_RADIUS)));//先将自己的头像显示出来
		query = (EditText) findViewById(R.id.query);
		String strSearch = getResources().getString(R.string.search);
		query.setHint(strSearch);
		clearSearch = (ImageButton) findViewById(R.id.search_clear);
		query.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (adapter != null) {
					adapter.getFilter().filter(s);
				}
				if (s.length() > 0) {
					clearSearch.setVisibility(View.VISIBLE);
				} else {
					clearSearch.setVisibility(View.INVISIBLE);
				}
			}

			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			public void afterTextChanged(Editable s) {
			}
		});
		clearSearch.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				query.getText().clear();
			//	hideSoftKeyboard();
			}
		});
		
		String groupId = getIntent().getStringExtra("groupId");
		if (groupId == null) {// 创建群组
			isCreatingNewGroup = true;
		} 
//		else {
//			// 获取此群组的成员列表
//			EMGroup group = EMClient.getInstance().groupManager().getGroup(groupId);
//			if (group != null) {
//				exitingMembers = group.getMembers();
//			}
//			
//		}
//		if(exitingMembers == null)
//			exitingMembers = new ArrayList<String>();

//		dialog = new LoadingFragment();
		initModels();
//		requestData();
	}

////	@Override
//	protected boolean handler(Message msg) {
//		// TODO Auto-generated method stub
////		if (super.handler(msg))
////			return true;
//		switch (msg.what) {
//		case MESSAGE_UPDATE_SEND_BTN:
////			int count = (int) msg.obj;
//			String count = (String) msg.obj;
////			sureBtn.setText("确定(" + count + ")");
//			break;
//		case MESSAGE_BIND_FRIEND_LIST:
//			bindAdapter();
//			break;
//		}
//		return false;
//	}

//	/**
//	 * 请求网络数据
//	 */
//	private void requestData() {
//		if (!isFinishing()) {
//			dialog.show(getSupportFragmentManager(), "Loading");
//			dialog.setMsg("加载中");
//		}
//		new Thread() {
//			@Override
//			public void run() {
//				friends = filterExistGroupMember(bindFriendListToSortModel2(FriendDao.getInstance(GroupPickContactsActivity.this).getFriendList()));
//				runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						handleData();
//					}
//				});
//			}
//		}.start();
//	}
//
//	private void handleData() {
//		if (dialog != null && dialog.getFragmentManager() != null
//				&& dialog.getDialog() != null && dialog.getDialog().isShowing()) {
//			dialog.dismissAllowingStateLoss();
//		}
//		if (friends.size() > 0) {
//			handler.sendEmptyMessage(MESSAGE_BIND_FRIEND_LIST);
//		} else {
//			if (!isNetWorkAvailable()) {
//				handler.obtainMessage(StringConfig.SHOW_TOAST,
//						getResources().getString(R.string.no_network))
//						.sendToTarget();
//			} else {
//				RequestServerManager.asyncRequest(0, new RequestFriendList(this, 0,
//						new RequestFinishCallback<FriendListResult>() {
//
//							@Override
//							public void onFinish(FriendListResult result) {
//								// TODO Auto-generated method stub
//								if (result.isSucceed()) {
//									friends = filterExistGroupMember(bindFriendListToSortModel2(result
//											.getFriends()));
//									handler.sendEmptyMessage(MESSAGE_BIND_FRIEND_LIST);
//								} else {
//									handler.obtainMessage(StringConfig.SHOW_TOAST,
//											result.getDescription()).sendToTarget();
//								}
//							}
//						}));
//			}
//		}
//	}
	
	private List<SortModel2> filterExistGroupMember(List<SortModel2> tmpList){
		List<SortModel2> result=new ArrayList<SortModel2>();
		for(SortModel2 item:tmpList){
			if(!exitingMembers.contains(item.getName())){
				result.add(item);
			}
		}
		return result;
	}

	private List<SortModel2> bindFriendListToSortModel2(List<ContactGroup> friends) {
		List<SortModel2> mSortList = new ArrayList<SortModel2>();
		for (ContactGroup item : friends) {
			if (item != null) {
				SortModel2 sort = new SortModel2();
				sort.setName(item.getUsername());
				sort.setImgUrl(item.getAvatarPath());
				sort.setUid(item.getUid());
				if (!TextUtils.isEmpty(sort.getName())) {
					String pinyin = characterParser.getSelling(sort.getName());
					if (!TextUtils.isEmpty(pinyin)) {
						String sortString = pinyin.substring(0, 1).toUpperCase();
						if (sortString.matches("[A-Z]")) {
							sort.setSortLetters(sortString.toUpperCase());
						} else {
							sort.setSortLetters("#");
						}
					} else {
						sort.setSortLetters("#");
					}
				} else {
					sort.setSortLetters("#");
				}

				mSortList.add(sort);
			}
		}
		return mSortList;
	}

	/**
	 * 初始化模块
	 */
	private void initModels() {
		// 字符串排序组件
		characterParser = CharacterParser.getInstance();
		// 中文排序组件
		pinyinComparator = new PinyinComparator();
	}

	/**
	 * 绑定适配器
	 */
	private void bindAdapter() {
//		Collections.sort(friends, pinyinComparator);
		Log.e("================GroupPickContactsActivity.java ================", "++++++++++++++friends_cGroup1111++++++++++++++"+cGroup);
        if(friends_cGroup!=null
        		&& friends_cGroup.size()!=0){
        	
        	for(int i=0;i<friends_cGroup.size();i++){
        		cGroup = (ContactGroup)friends_cGroup.get(i);
        		Log.e("================GroupPickContactsActivity.java ================", "++++++++++++++friends_cGroup2222++++++++++++++"+cGroup.toXML());
        		cgrouptype = cGroup.getType();////0 contact,1 group
        		if(cgrouptype == 1)
        			friends_cGroup.remove(i);
        	}
        	friends = filterExistGroupMember(bindFriendListToSortModel2(friends_cGroup));
        	Log.e("================GroupPickContactsActivity.java ================", "++++++++++++++friends.size3333++++++++++++++"+friends.size());
        }
		
		adapter = new SortAdapter2(this, friends, listener);
		adapter.updateListView(member);
		batchFriendList.setAdapter(adapter);
		batchFriendList.setDividerHeight(0);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
//		switch (v.getId()) {
//		case R.id.sendBtn:
//			if(adapter!=null){
//				List<String> checkMaps = adapter.getCheckMaps();
//				if (checkMaps.size() <= 0)
//					handler.obtainMessage(StringConfig.SHOW_TOAST, "请勾选需要的好友")
//							.sendToTarget();
//				else {
//					if (type == 0) {
//						setResult(RESULT_OK, new Intent().putExtra("newmembers", getTobeAddedList(checkMaps).toArray(new String[0])));
//						finish();
//					} else {
//
//						int w = 0;
//						for (String userid : getTobeAddedList(checkMaps)) {
//							String userName = adapter.getCheckMapsName().get(w);
//	                     	String userAvatar = adapter.getCheckMapsUrl().get(w);
//	                     	w++;
//						
//		                 if (userid.equals(CurrentUid))
//		                     {Toast.makeText(GroupPickContactsActivity.this, R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();}
//		                 else {
//		                     // 进入聊天页面
////		                     Intent intent = new Intent(GroupPickContactsActivity.this, ChatActivity.class);
////		                     	
////		                           intent.putExtra(EaseConstant.EXTRA_USER_NAME, userName);
////		                           intent.putExtra(EaseConstant.EXTRA_USER_AVATAR, userAvatar);
////		                     // it's single chat
////		                     intent.putExtra(EaseConstant.EXTRA_USER_ID, userid);
////		                     intent.putExtra("forward_msg_id", id);
////							 intent.putExtra("link_share", link_share);
////							 intent.putExtra("txt", txt);
////		                     startActivity(intent);
////		                     if (w== getTobeAddedList(checkMaps).size()) {
////		                    	 finish();
////							 }
//		                     
//		                 }
//						}
//					}
//					
//				}
//			}else {
//				handler.obtainMessage(StringConfig.SHOW_TOAST, "没有好友数据，无法选择").sendToTarget();
//				setResult(RESULT_CANCELED);
//				finish();
//			}
//			break;
//		}
	}

	private List<String> getTobeAddedList(List<String> checkMaps) {
		List<String> result = new ArrayList<String>();
		for (int i = 0; i < checkMaps.size(); i++) {
//				result.add("user_"+checkMaps.get(i));
			result.add(checkMaps.get(i));
		}
		return result;
	}
	
	
	private IRoster mRoster;
	 private HashMap cGroups = new HashMap();
	    private ArrayList cGroupsList = new ArrayList<ContactGroup>();
	    int AffiliationsCount = 0;
	    private String OwnerUid = "";
	    private String OwnerUsername = "";
	    private String CurrentUid = "";
	    private String CurrentUsername = "";
		private String[] errorMsg = new String[]{"群成员信息获取成功.",
				"服务连接中1-1,请稍候再试.",
				"服务连接中1-2,请稍候再试.",
				"服务连接中1-3,请稍候再试.",
				"网络连接不可用,请检查你的网络设置.",
				"系统错误.群成员信息获取失败.",
				"群成员信息获取失败,hash校验失败"//0002
				};
		private int errorType = 5;
	    private boolean initGeGroupMembers(String tagid,String page,String keystr){//page=1 keystr=""
//	    	showCustomToast("initGeGroupMembers1");
	    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers1111++++++++++++++");
			try{
				if(BeemConnectivity.isConnected(getApplicationContext())){
					Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers2222++++++++++++++");
			    if(mXmppFacade!=null 
						&& mXmppFacade.getXmppConnectionAdapter()!=null 
						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
						){
			    	    mRoster = mXmppFacade.getXmppConnectionAdapter().getRoster();
			    	    friends_cGroup = mRoster.getContactList();//List<ContactGroup>
			    	    Log.e("响应packet结果解析friends_cGroup...............", "friends_cGroup="+friends_cGroup.size()); 
			    			    					GroupPickContactsActivity.this.runOnUiThread(new Runnable() {
			    				                    	
			    		    							@Override
			    		    							public void run() {
			    		    								showCustomToast("服务器应答消息：friends_cGroup.size()="+friends_cGroup.size());
			    		    							}
			    		    						});
			    	    
			    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers3333++++++++++++++");
			    	    ViewGroupMemberIQ reqXML = new ViewGroupMemberIQ();
			            reqXML.setId("1234567890");
			            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
			            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
			            CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
			            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
			    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
			    	    CurrentUsername = username;
//			            reqXML.setUsername(username);
			            reqXML.setTagid(tagid);
			            reqXML.setPage(page);
			            reqXML.setKeystr(keystr);
			            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
			            reqXML.setUuid(uuid);
		//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
			            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid;
			            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
			            reqXML.setHashcode(hash_dest);
			            reqXML.setType(IQ.Type.SET);
			            String elementName = "viewgroupmemberiq"; 
			    		String namespace = "com:isharemessage:viewgroupmemberiq";
			    		ViewGroupMemberIQResponseProvider provider = new ViewGroupMemberIQResponseProvider();
			            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "viewgroupmemberiq", "com:isharemessage:viewgroupmemberiq", provider);
			            
			            if(rt!=null){
			                if (rt instanceof ViewGroupMemberIQResponse) {
			                	final ViewGroupMemberIQResponse viewGroupMemberIQResponse = (ViewGroupMemberIQResponse) rt;
		
			                    if (viewGroupMemberIQResponse.getChildElementXML().contains(
			                            "com:isharemessage:viewgroupmemberiq")) {
		//	    					MainActivity.this.runOnUiThread(new Runnable() {
		//		                    	
		//    							@Override
		//    							public void run() {
		//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
		//    							}
		//    						});
			                        String Id = viewGroupMemberIQResponse.getId();
			                        String Apikey = viewGroupMemberIQResponse.getApikey();
			                        cGroups = viewGroupMemberIQResponse.getCGroups();
			                        AffiliationsCount = cGroups.size();
			                        if(cGroups.size()!=0){
				                        Log.e("响应packet结果解析...............", "Id="+Id+";Apikey="+Apikey); 
//				                        return true;
				                        Iterator iter = cGroups.entrySet().iterator();
				            			Map.Entry entry = null;
				            			Object key = null;
				            			Object val = null;
				            			ContactGroup cGroup = null;
				            			while (iter.hasNext()) {
				                			entry = (Map.Entry) iter.next();
				                			key = entry.getKey();
				                			val = entry.getValue();
				                			cGroup = (ContactGroup)val;
				                			cGroupsList.add(cGroup);
				                			exitingMembers.add(cGroup.getUsername());
				                			//isfriend=true;2@0/allen
				                			System.out.println("al_rec.size()="+cGroups.size()+"uid-isfriend="+key+";"+cGroup.getUid()+"@0/"+cGroup.getUsername());
				                			if(((String)key).indexOf("0")!=-1){
				                				OwnerUid = cGroup.getUid();
				                				OwnerUsername = cGroup.getUsername();
//				                				break;
				                			}
				            			}
			                        }
			                        String retcode = viewGroupMemberIQResponse.getRetcode();
			                        String memo = viewGroupMemberIQResponse.getMemo();
			                        if(retcode.equalsIgnoreCase("0000")){
			                        	errorType = 0;
			                        	return true;
			                        }
			                        else if(retcode.equalsIgnoreCase("0002"))
			                        	errorType = 6;
			                        else
			                        	errorType = 5;
			                        
			                    }
			                } 
			            }
			    		errorType = 1;

			    }else
			    	errorType = 1;
			    
				}else
					errorType = 4;
			}catch(RemoteException e){
				e.printStackTrace();
				errorType = 2;
			}catch(Exception e){
				e.printStackTrace();
				errorType = 3;
			}
			return false;
	    }
	    
	    private boolean flag = false;
		private boolean isWork = false;
		private void getGroupMembers(final String tagid) {
//			showCustomToast("getGroupMembers1");
			Log.e("================GroupDetailsActivity.java ================", "++++++++++++++getGroupMembers111++++++++++++++");
			if(!isWork){
			putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					showLoadingDialog("正在加载,请稍后...");
				}

				@Override
				protected Boolean doInBackground(Void... params) {
					return initGeGroupMembers(tagid,"1","");
				}

				@Override
				protected void onPostExecute(Boolean result) {
					super.onPostExecute(result);
					dismissLoadingDialog();
					if (result) {	
//						mHandler.sendEmptyMessage(1);
						mHandler.sendEmptyMessage(MESSAGE_BIND_FRIEND_LIST);
					}else{
						//提示没有获取到数据：可能网络问题
//						mHandler.sendEmptyMessage(0);
					}
					flag = false;
					isWork = false;
				}

			});
			isWork = true;
			}
		}
	/**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {
		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
//		    	try{
//			    	CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
//		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
//		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
//		    	    CurrentUsername = username;
//		    	}catch(Exception e){
//		    		e.printStackTrace();
//		    	}
	    	    mBinded = true;//20130804 added by allen
		    }
		    if(groupId!=null
		    		&& !groupId.equalsIgnoreCase("null")
		    		&& groupId.length()!=0)
		    	getGroupMembers(groupId);
		    else
		    	getGroupMembers("1");//测试用
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
		    mXmppFacade = null;
		    mBinded = false;
		}
    }

	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(GroupPickContactsActivity.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(GroupPickContactsActivity.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
	
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
//			getContactList(ConstantValues.refresh);
//			startActivity(new Intent(OtherProfileActivity.this, ContactFrameActivity.class));//ContactListPullRefListActivity
			Intent intent =  new Intent(GroupPickContactsActivity.this, ContactFrameActivity.class);
	    	intent.putExtra("refreshroster", "true");
			startActivity(intent);
			GroupPickContactsActivity.this.finish();
		}
	}
	
	protected class OnMiddleImageButtonClickListener implements
	onMiddleImageButtonClickListener {

		@Override
		public void onClick() {
			if(adapter!=null){
				List<String> checkMaps = adapter.getCheckMaps();
				if (checkMaps.size() <= 0)
					mHandler.obtainMessage(StringConfig.SHOW_TOAST, "请勾选需要的好友")
							.sendToTarget();
				else {
					if (type == 0) {
						setResult(RESULT_OK, new Intent().putExtra("newmembers", getTobeAddedList(checkMaps).toArray(new String[0])));
						finish();
					} else {

						int w = 0;
						for (String userid : getTobeAddedList(checkMaps)) {
							String userName = adapter.getCheckMapsName().get(w);
	                     	String userAvatar = adapter.getCheckMapsUrl().get(w);
	                     	w++;
						
		                 if (userid.equals(CurrentUid))
		                     {Toast.makeText(GroupPickContactsActivity.this, R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();}
		                 else {
		                     // 进入聊天页面
//		                     Intent intent = new Intent(GroupPickContactsActivity.this, ChatActivity.class);
//		                     	
//		                           intent.putExtra(EaseConstant.EXTRA_USER_NAME, userName);
//		                           intent.putExtra(EaseConstant.EXTRA_USER_AVATAR, userAvatar);
//		                     // it's single chat
//		                     intent.putExtra(EaseConstant.EXTRA_USER_ID, userid);
//		                     intent.putExtra("forward_msg_id", id);
//							 intent.putExtra("link_share", link_share);
//							 intent.putExtra("txt", txt);
//		                     startActivity(intent);
//		                     if (w== getTobeAddedList(checkMaps).size()) {
//		                    	 finish();
//							 }
		                     
		                 }
						}
					}
					
				}
			}else {
				mHandler.obtainMessage(StringConfig.SHOW_TOAST, "没有好友数据，无法选择").sendToTarget();
				setResult(RESULT_CANCELED);
				finish();
			}
		}
	}
	
	@Override
    protected void onResume() {
    	Log.e("================20170507 MainListActivity onResume================", "+++++++onResume+++++++");
		super.onResume();
		isWork = false;
		if (!mBinded){
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);	    
		}
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearAsyncTask();
        if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}
		mXmppFacade = null;
    }

}
